
package com.china08.yxyapi.api.manage.stu.mystudy.mistakes;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.es.ElasticYxyYxyQuesResource;
import com.china08.yxyapi.entity.mg.mistakes.StuMistakesQues;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.es.ElasticYxyYxyQuesResourceRespository;
import com.china08.yxyapi.repository.mg.mistakes.StuMistakesQuesRepository;
import com.china08.yxyapi.util.DateToolUtils;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;

/**
 * 错题本--学生端--错题展示
 *
 * @author LiuWeidong
 *
 */
@CrossOrigin
@RestController
public class MistakesSubjectQuesSrhController extends YxyApiBaseController {

    @Autowired
    private StuMistakesQuesRepository stuMistakesQuesRepository;

    @Autowired
    private ElasticYxyYxyQuesResourceRespository elasticYxyYxyQuesResourceRespository;

    @RequestMapping(value = "/api_yw/manage/stu/mystudy/mistakes/srh1", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Page<RespModel> precess(HttpServletRequest request, HttpServletResponse response,
            @RequestBody ReqModel reqModel)
                    throws ParseException, JsonParseException, JsonMappingException, IOException {

        String studentId = reqModel.studentId;
        String subject = reqModel.subject;
        List<String> subjectLst = new ArrayList<>();
        subjectLst.add(subject);

        Integer status = reqModel.status;
        Integer focus = reqModel.focus;
        Date startDate = reqModel.startDate;
        Date endDate = reqModel.endDate;
        String schoolType = reqModel.schoolType;

        // 试题类型
        List<String> questionTypeLst = new ArrayList<>();
        questionTypeLst.add("0");
        questionTypeLst.add("1");
        questionTypeLst.add("3");
        questionTypeLst.add("4");

        Pageable pageable = reqModel.getPageable(Direction.DESC, "createdDate");
        List<RespModel> returnList = new ArrayList<>();
        Page<StuMistakesQues> stuMistakesQuesPage = new PageImpl<>(new ArrayList<StuMistakesQues>());

        // 小学科目（语文，数学，英语）
        String[] gradeSubjectName = new String[] { "jcsub01", "jcsub02", "jcsub03" };
        List<String> gradeSubjectNotLst = Arrays.asList(gradeSubjectName);

        // 初高中科目（ 语文,数学,英语,物理,化学,生物,政治,历史,地理）
        String[] middleSubjectName = new String[] { "jcsub01", "jcsub02", "jcsub03", "jcsub13", "jcsub14", "jcsub15",
                "jcsub09", "jcsub11", "jcsub12" };
        List<String> middleSubjectNotLst = Arrays.asList(middleSubjectName);

        /**
         * 如果学校类型为小学时，学科显示为语、数、外、其它
         * 错题划分（focus）为2时，查询划分全部的错题；错题划分（focus）为1时，查询划分为重点题的错题
         * 学科类型（subject）为null时查询其它，反之按学科类型查询
         */
        if (schoolType == "ST1") {
            /* 错题划分：全部 */
            if (focus == 2) {
                // 查询非其它学科
                if (subject != null) {
                    stuMistakesQuesPage = stuMistakesQuesRepository
                            .findByStudentIdAndSubjectInAndStatusAndQuestionTypeInAndPublishDateBetween(studentId,
                                    subjectLst, status, questionTypeLst, startDate, endDate, pageable);
                } // 查询其它学科
                else {
                    stuMistakesQuesPage = stuMistakesQuesRepository
                            .findByStudentIdAndSubjectNotInAndStatusAndQuestionTypeInAndPublishDateBetween(studentId,
                                    gradeSubjectNotLst, status, questionTypeLst, startDate, endDate, pageable);
                }

            }

            /* 错题划分：重点题 */
            else {
                // 查询非其它学科
                if (subject != null) {
                    stuMistakesQuesPage = stuMistakesQuesRepository
                            .findByStudentIdAndSubjectInAndStatusAndQuestionTypeInAndFocusAndPublishDateBetween(
                                    studentId, subjectLst, status, questionTypeLst, focus, startDate, endDate,
                                    pageable);
                } // 查询其它学科
                else {
                    stuMistakesQuesPage = stuMistakesQuesRepository
                            .findByStudentIdAndSubjectNotInAndStatusAndQuestionTypeInAndFocusAndPublishDateBetween(
                                    studentId, gradeSubjectNotLst, status, questionTypeLst, focus, startDate, endDate,
                                    pageable);
                }
            }
        }
        /**
         * 如果学校类型为初中高中时，学科显示为语、数、外、物、化、生、其它
         * 错题划分（focus）为2时，查询划分全部的错题；错题划分（focus）为1时，查询划分为重点题的错题
         * 学科类型（subject）为null时查询其它，反之按学科类型查询
         */
        else {
            /* 错题划分：全部 */
            if (focus == 2) {
                // 查询非其它学科
                if (subject != null) {
                    stuMistakesQuesPage = stuMistakesQuesRepository
                            .findByStudentIdAndSubjectInAndStatusAndQuestionTypeInAndPublishDateBetween(studentId,
                                    subjectLst, status, questionTypeLst, startDate, endDate, pageable);
                } // 查询其它学科
                else {
                    stuMistakesQuesPage = stuMistakesQuesRepository
                            .findByStudentIdAndSubjectNotInAndStatusAndQuestionTypeInAndPublishDateBetween(studentId,
                                    middleSubjectNotLst, status, questionTypeLst, startDate, endDate, pageable);
                }
            }
            /* 错题划分：重点题 */
            else {

                // 查询非其它学科
                if (subject != null) {
                    stuMistakesQuesPage = stuMistakesQuesRepository
                            .findByStudentIdAndSubjectInAndStatusAndQuestionTypeInAndFocusAndPublishDateBetween(
                                    studentId, subjectLst, status, questionTypeLst, focus, startDate, endDate,
                                    pageable);
                } // 查询其它学科
                else {
                    stuMistakesQuesPage = stuMistakesQuesRepository
                            .findByStudentIdAndSubjectNotInAndStatusAndQuestionTypeInAndFocusAndPublishDateBetween(
                                    studentId, middleSubjectNotLst, status, questionTypeLst, focus, startDate, endDate,
                                    pageable);
                }
            }
        }

        for (StuMistakesQues stuMistakesQues : stuMistakesQuesPage) {
            RespModel model = new RespModel();
            model.sources = stuMistakesQues.getSources();
            String aa = DateToolUtils.format(stuMistakesQues.getPublishDate(), DateToolUtils.FORMAT_LONG);
            model.publishDate = aa;
            ElasticYxyYxyQuesResource ryyqr = elasticYxyYxyQuesResourceRespository
                    .findById(stuMistakesQues.getQuesId());
            model.ques = ryyqr == null ? null : ryyqr.getQuesBody();
            model.mistakesReason = stuMistakesQues.getMistakesReason();
            model.status = stuMistakesQues.getStatus();
            model.focus = stuMistakesQues.getFocus();
            model.questionType = stuMistakesQues.getQuestionType();
            model.quesId = stuMistakesQues.getQuesId();
            model.id = stuMistakesQues.getId();

            if (stuMistakesQues.getAnswerOfMy() != null) {
                if (stuMistakesQues.getAnswerOfMy().equals("")) {
                    model.answerOfMy = "您没有作答！";
                } else if (stuMistakesQues.getAnswerOfMy().equals(null)) {
                    model.answerOfMy = "您没有作答！";
                } else {
                    model.answerOfMy = stuMistakesQues.getAnswerOfMy();
                }
            }

            if (stuMistakesQues.getAnswerText() != null) {
                if (stuMistakesQues.getAnswerText().equals("")) {
                    model.answerText = "您没有作答！";
                } else if (stuMistakesQues.getAnswerText().equals(null)) {
                    model.answerText = "您没有作答！";
                } else {
                    model.answerText = stuMistakesQues.getAnswerText();
                }
            }

            if (stuMistakesQues.getAnswerImgs() != null) {
                List<String> answerImgsLst = new ArrayList<String>();
                answerImgsLst.add("不能查看答案！");
                if (stuMistakesQues.getAnswerImgs().equals("")) {
                    model.answerImgs = answerImgsLst;
                } else if (stuMistakesQues.getAnswerImgs().equals(null)) {
                    model.answerImgs = answerImgsLst;
                } else {
                    model.answerImgs = stuMistakesQues.getAnswerImgs();
                }
            }
            model.answerImgs = stuMistakesQues.getAnswerImgs();
            returnList.add(model);
        }
        Page<RespModel> respModelpage = new PageImpl<MistakesSubjectQuesSrhController.RespModel>(returnList, pageable,
                stuMistakesQuesPage.getTotalElements());

        return respModelpage;
    }

    /* 请求参数 */
    protected static class ReqModel extends YxyApiPageReqModel {
        // 学生ID
        public String studentId;
        // 学科
        public String subject;
        // 状态： 0--未消灭 1--已消灭
        public Integer status;
        // 划分：0--普通 1--重点题--2--全部
        public Integer focus;
        // 筛选开始时间
        public Date startDate;
        // 筛选结束时间
        public Date endDate;
        // 是否其它，是：1，否：0
        public String state;
        // 学校类型
        public String schoolType;
    }

    /* 响应参数 */
    protected static class RespModel extends YxyApiRespModel {
        // ID
        public String id;
        // 错题来源, 可能来源多个
        public List<String> sources;
        // 答题时间
        public String publishDate;
        // 试题
        public Object ques;
        // 错误原因, 存储中文, 使用逗号分割
        public List<String> mistakesReason;
        // 是否消灭： 0--未消灭 1--已消灭
        public Integer status;
        // 是否重点题：0--普通 1--重点题
        public Integer focus = 0;
        // 试题类型
        public String questionType;
        // 试题ID
        public String quesId;
        // 答案 0--单选择题，1--多选择题
        public String answerOfMy;
        // 答案2--通知类，3--填空，4--问答
        public String answerText;
        // 主观题, 通知类回答 上传的图片
        public List<String> answerImgs;
    }

}
